﻿using AutoMapper;
using BackData;
using Domain;
using Domain.DTOs;
using Infratructure;
using MediatR;
using SqlSugar;
using System.Linq;
using Team.API.Applocation.Command.BOM;

namespace Team.API.Applocation.Hanldler.BOM
{
    public class BOMfinishedNlogHandler:IRequestHandler<BOMfinishedNlogCommand, APIResult<OneNlogDTO>>
    {
        private readonly IRepository<Nlogmodel> nlogway;
        private readonly IMapper mapper;

        public BOMfinishedNlogHandler(IRepository<Nlogmodel> nlogway,IMapper mapper)
        {
            this.nlogway = nlogway;
            this.mapper = mapper;
        }
        /// <summary>
        /// BOM操作日志
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIResult<OneNlogDTO>> Handle(BOMfinishedNlogCommand request, CancellationToken cancellationToken)
        {
            var res = new APIResult<OneNlogDTO>();

            if (request.Id <= 0)
            {
                res.Code = StateCode.Fail;
                res.Message = "BOM ID无效";
                return res;
            }

            var latestLog = await nlogway.GetAll()
                .Where(x => x.Category == "BOM" && x.Otherkey == request.Id && x.IsDel == false)
                //.OrderByDescending(x => x.Createtime)
                .Take(1)
                .ToListAsync();

            var value = latestLog.FirstOrDefault();
            if (value != null)
            {
                res.Code = StateCode.OK;
                res.Message = "获取成功";
                res.Result = mapper.Map<OneNlogDTO>(value);
            }
            else
            {
                res.Code = StateCode.OK;
                res.Message = "暂无操作记录";
                res.Result = null;
            }

            return res;
        }
    }
}
